<template>
  <div class="hechart" ref="mychart"></div>
</template>

<script setup>
import * as echarts from "echarts";
import { onMounted, getCurrentInstance, watch, reactive } from "vue";
import { barData } from "@/mockApi/homepage/MockBarData";

let currentInstance = "";
currentInstance = getCurrentInstance(); // 获取组件实例
// const props = defineProps({
//   cData: {
//     type: Object,
//   },
// });

let xData = reactive([]);
let yData = reactive([]);
// 柱状图轮播数据请求
const getBarData = () => {
  barData.getAll().then((res) => {
    const x = JSON.parse(JSON.stringify(res[0]?.xAxis?.data));
    const y = JSON.parse(JSON.stringify(res[0]?.yAxis?.data));
    xData.push(x);
    yData.push(y);
    // console.log(xData, yData, "111");
  });
};

onMounted(async () => {
  getBarData();
  initCharts();
  setOptions();
});

watch(xData, (newValue, oldValue) => {
  console.log("数据发生变化", newValue, oldValue);
  setOptions();
});
let chart = "";

// 初始化
const initCharts = () => {
  chart = echarts.init(currentInstance.ctx.$refs.mychart);
  window.addEventListener("resize", function () {
    chart.resize();
  });
};

const setOptions = () => {
  // console.log("传入的三角柱状图数据", xData, yData);
  // 基本柱状图
  const option = {
    title: {
      text: "小区单元人数",
      textStyle: {
        color: "rgba(225, 225, 225)",
        fontFamily: "Microsoft YaHei",
        fontSize: 14,
        fontWeight: "normal",
      },
      left: 10,
      top: 10,
    },
    xAxis: {
      type: "category",
      data: ["单元1", "单元2", "单元3", "单元4", "单元5"],
      interval: 24,
      axisLabel: {
        show: true,
        textStyle: {
          color: "#ffffff",
        },
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        show: true,
        textStyle: {
          color: "#ffffff",
        },
      },
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: "bar",
        showBackground: false,
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)",
        },
      },
    ],
  };
  //   console.log(option);
  chart.setOption(option);
};
</script>

<style lang="scss">
.hechart {
  width: 100%;
  height: 100%;
}
</style>
